﻿using GameProject.Models;
using GameProject.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GameProject.Service
{
	public class GameInstanceService
	{
		private IAppRepository repository;
		
		public GameInstanceService()
		{
			repository = new AppRepository();
		}

		public GameInstanceService(IAppRepository repository)
		{
			this.repository = repository;
		}
		/// <summary>
		/// Function that returns the game ID
		/// </summary>
		/// <param name="gameId">The ID of the game</param>
		/// <returns>The game ID</returns>
		public GameInstance GetGameById(int gameId)
		{
			return repository.GetGames().First(x => x.ID == gameId);
		}

		/// <summary>
		/// Function that returns all the games that have the status "Waiting for players".
		/// </summary>
		/// <returns>Games with the status "Waiting for players"</returns>
		public IEnumerable<GameInstance> GetWaitingGames()
		{
			return repository.GetGames().Where(x => x.Status == GameStatus.WAITING_FOR_PLAYERS).ToList();
		}

		/// <summary>
		/// Function that adds a game instance
		/// </summary>
		/// <param name="game">The game being added</param>
		public void AddGameInstance(GameInstance game)
		{
			repository.AddGameInstance(game);
		}		
	
		/// <summary>
		/// Function that returns the users playing in a specific game.
		/// </summary>
		/// <param name="gameTypeId">The ID of the game type, e.g. 1 for Snakes and Ladders and 2 for Connect4</param>
		/// <returns>Users with the status "Playing" in a specific game type</returns>
		public List<string> GetActiveUsersForGameType(int gameTypeId)
		{
			HashSet<string> returnValue = new HashSet<string>();

			IEnumerable<GameInstance> activeGames = repository.GetGames().Where(x => x.Status == GameStatus.PLAYING && x.GameType.ID == gameTypeId);
			foreach (GameInstance game in activeGames)
			{
				foreach (Piece piece in game.PieceSnakes)
				{
					if (!piece.IsComputerPlayer)
					{
						returnValue.Add(piece.User.UserName);
					}
				}
			}
			return returnValue.ToList();
		}

		/// <summary>
		/// Function that gets users by ID
		/// </summary>
		/// <param name="id">ID of the player</param>
		/// <returns>User with a specific ID</returns>
		public UserProfile GetUserById(int id)
		{
			return repository.GetUsers().First(x => x.UserId == id);
		}

		/// <summary>
		/// Function that returns game type by ID
		/// </summary>
		/// <param name="gameTypeId">The ID for the game type, e.g. 1 for Snakes and Ladders, 2 for Connect4</param>
		/// <returns>Game type for a specific ID</returns>
		public GameType GetGameTypeById(int gameTypeId)
		{
			return repository.GetGameTypes().First(x => x.ID == gameTypeId);
		}

		/// <summary>
		/// Function that saves to the database.
		/// </summary>
		public void Save()
		{
			repository.Save();
		}
	}
}